/*
 * @# PhotoFavorServiceImpl.java 2011-12-31 上午11:20:20
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.album.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.ianswer.common.orm.PublicDao;
import com.ianswer.common.util.time.SecondsUtils;
import com.ianswer.px.album.entity.PhotoFavor;
import com.ianswer.px.album.redis.PhotoRedis;
import com.ianswer.px.album.service.PhotoFavorService;
import com.ianswer.px.user.entity.UserBaseInfo;

/**
 * @author alvin hwang
 */
@Service("photoFavorService")
public class PhotoFavorServiceImpl implements PhotoFavorService {

	@Resource(name = "publicDao")
	private PublicDao publicDao;
	
	@Override
	public List<PhotoFavor> queryFirstPageByUser(Long userId) {
		return queryByUser(userId, 1);
	}
	
	@Override
	public List<PhotoFavor> queryByUser(Long userId, int pageIndex) {
		PhotoFavor cond = new PhotoFavor();
		cond.setUserId(userId);
		
		List<PhotoFavor> favors = publicDao.query("photosFavors.query", cond);
		if (CollectionUtils.isEmpty(favors)) {
			return new ArrayList<PhotoFavor>();
		}
		for (PhotoFavor favor : favors) {
			favor.setAuthor(UserBaseInfo.get(favor.getAuthorId()));
		}
		return favors;
	}

	@Override
	public Long insert(Long albumId, Long photoId, Long userId) {
		PhotoFavor favor = new PhotoFavor();
		favor.setAlbumId(albumId);
		favor.setPhotoId(photoId);
		favor.setUserId(userId);
		favor.setCreatedAt(SecondsUtils.seconds());
		
		Long favorId = (Long) publicDao.insert("photosFavors.insert", favor);
		
		PhotoRedis.incrFavors(photoId);
		
		return favorId;
	}

	@Override
	public void delete(Long albumId, Long photoId, Long userId) {
		PhotoFavor favor = new PhotoFavor();
		favor.setAlbumId(albumId);
		favor.setPhotoId(photoId);
		favor.setUserId(userId);
		
		 publicDao.delete("photosFavors.delete", favor);
		
		PhotoRedis.decrFavors(photoId);
	}

}
